const express = require('express');
const monge = require('../utils/mongo');
// 数据交互格式化
const formatData = require('../utils/tool');
// 内置加密模块
const crypto = require('crypto');
// token令牌
const token = require('../utils/token');
const router = express.Router();

// 1.获取所有用户
router.get('/',async(req,res)=>{
    try{
        const result = await monge.find('user',{},{
            field:{password:false}
        })
        res.send(formatData({data:result}))
    }catch(err){
        res.send({code:0})
    }
})

// 7.获取当前用户信息
router.get('/:id',async(req,res)=>{
    let {id} = req.params;
    try{
        const result = await monge.find('user',{_id:id},{
            /* 过滤密码 */
            field:{password:false}
        })
        res.send(formatData({data:result}))
    }catch(err){
        res.send({code:0})
    }
})

// 2.注册
router.post('/reg',async(req,res)=>{
    let {username,password} = req.body;

    // 对密码进行加密
    const hashPw = crypto.createHash('md5');
    hashPw.update(password+'jiami');    // 加密优化：加盐操作，jiami为盐值
    password = hashPw.digest('hex');

    // console.log(password);

    try{
        const result = await monge.insert('user',{username,password})
        res.send(formatData())
    }catch(err){
        res.send(formatData({code:0}))
    }
})

// 3.验证用户名
router.get('/check',async(req,res)=>{
    let {username} = req.query;

    const result = await monge.find('user',{username});

    // 根据返回数组的长度进行判断：存在长度大于0，不存在长度为0
    if(result.length>0){
        res.send(formatData({code:0}))
    }else{
        res.send(formatData())
    }
})

// 4.登录
router.post('/login',async(req,res)=>{
    let {username,password,vcode,passLogin} = req.body;

    // c.校验验证码
    if(vcode !== req.session.vcode){
        res.send(formatData({code:2}))
        // 终止后续执行
        return
    }
    
    // a.密码转为密文处理
    const hashPw = crypto.createHash('md5');
    hashPw.update(password+'jiami');
    password = hashPw.digest('hex');

    // b.根据返回结果的长度判断是否有该帐密
    let result = await monge.find('user',{username,password});
    let authorization;

    if(result.length>0){
        // d. 帐密、验证码通过后，验证码免登陆
        if(passLogin==='true'){
            // 勾上则生成token
            authorization = await token.encrypt({username});
        }else{
            authorization = await token.encrypt({username},'3h');
        }
        // 把token写入用户信息中
        result[0].authorization = authorization;
        delete result[0].password;
        res.send({
            data:result
        })
    }else{
        res.send(formatData({code:0}))
    }
})

// 5.删除用户
router.delete('/:id',async(req,res)=>{
    let {id} = req.params;
    
    try{
        const result = await monge.remove('user',{_id:id});
        res.send(formatData())
    }catch(err){
        console.log(err);
        res.send(formatData({code:0}))
    }
})

// 6.修改用户信息
router.put('/:id',async(req,res)=>{
    let {id} = req.params;
    let {password,gender,age,phone,isSingle} = req.body;
    // console.log(id,password,gender,age,phone,isSingle);

    let newData = {gender,age,phone,isSingle};

    if(password){
        const hashPw = crypto.createHash('md5');
        hashPw.update(password+'jiami');
        password = hashPw.digest('hex');
        newData.password = password;
    }

    try{
        let result = monge.update('user',{_id:id},{$set:{...newData}})
        res.send(formatData());
    }catch(err){
        res.send(formatData({code:0}));
    }
})

module.exports = router;



